<template>
  <div class="edit-form">
    <header>
      <div class="title">
        {{ oprType && oprType === OPR_TYPE.ADD ? "新增" : "编辑" }}资源
      </div>
      <el-button-group>
        <el-button
          size="small"
          round
          @click="goBack"
        >返回
        </el-button>
        <el-button
          type="primary"
          size="small"
          round
          @click="handleSubmit"
        >保存
        </el-button>
      </el-button-group>
    </header>
    <div class="main">
      <el-form
        ref="ruleForm"
        :model="formData"
        :rules="rules"
        label-width="200px"
      >
        <el-form-item label="门店:" prop="shopId">
          <el-select v-model="formData.shopId" size="small" placeholder="请选择" clearable filterable @change="changeSelect">
            <el-option
              v-for="item in shopList"
              :key="item.shopId"
              :label="item.name"
              :value="item.shopId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="资源名称:" prop="name">
          <el-input
            v-model="formData.name"
            size="small"
            placeholder="请输入资源名称,限15个字"
            clearable
            maxlength="15"
          />
        </el-form-item>

        <el-form-item label="资源图片：" prop="imgUrl">
          <el-upload
            class="app-uploader-img-plus fl"
            :action="actionUrl"
            :show-file-list="false"
            :headers="{ 'X-BUSINESS-TOKEN': $store.state.user.token }"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.imgUrl" :src="formData.imgUrl" class="avatar">
            <i v-else class="el-icon-plus app-uploader-img-plus-icon" />
          </el-upload>
          <ul class="fl upload_tips">
            <li>图片要求：</li>
            <li>1.上传的图片限制文件大小不超过1MB，仅支持JPG/PNG格式</li>
          </ul>
        </el-form-item>

        <el-form-item v-if="oprType === OPR_TYPE.ADD" label="关联员工(用于通知):" prop="userIds">
          <!-- multiple 当前期改来改去仅支持单选，为了方便后端不用修改字段 -->
          <el-select v-model="formData.userIds" v-loadMore="loadMore" size="small" clearable filterable default-first-option placeholder="请选择">
            <el-option
              v-for="(item,index) in options.row"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <span class="i">不关联则不会发送通知哦（超过20条数据请下滑加载更多内容）</span>
        </el-form-item>
        <el-form-item v-else label="关联员工(用于通知):" prop="userId">
          <el-select v-model="formData.userId" v-loadMore="loadMore" size="small" clearable filterable default-first-option placeholder="请选择">
            <el-option
              v-for="(item,index) in options.row"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <span class="i">不关联则不会发送通知哦（超过20条数据请下滑加载更多内容）</span>
        </el-form-item>
        <el-form-item label="关联等级:" prop="levelId">
          <el-select v-model="formData.levelId" placeholder="请选择" size="small" clearable>
            <el-option
              v-for="item in levelList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
          <span class="i">若不关联等级时，该资源则不会有等级价格哦~</span>
        </el-form-item>

        <el-form-item label="标签:" class="labelList">
          <div
            style="margin-bottom: 10px"
          >
            <el-tag v-for="(item, index) in formData.labelList" :key="index" style="margin-right: 10px" closable @close="index=>{formData.labelList.splice(index, 1)}">{{ item
            }}</el-tag>
          </div>
          <el-input
            v-model.trim="tagValue"
            type="text"
            size="small"
            maxlength="8"
            clearable
            placeholder="请输入内容按Enter键添加"
            @keyup.enter.native="addShopLabel()"
          />
        </el-form-item>

        <el-form-item label="状态:" prop="status">
          <el-switch
            v-model="formData.status"
            :active-value="LIST_STATE.ON"
            :inactive-value="LIST_STATE.OFF"
          />
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import {
  OPR_TYPE,
  LIST_STATE
} from '@/views/wxaReservationModule/views/resourceManage/config'
import { imgUploadUrl } from '@/api/upload'
import {
  addAppointmentCategoryDetail,
  getAppointmentCategoryDetail,
  getAppointmentLevelLis,
  updateAppointmentCategoryDetail,
  selectShopUser
} from '@/api/reservation'

export default {
  name: 'Index',
  directives: {
    loadMore: {
      bind(el, binding) {
        // 获取element，定义scroll
        const select_dom = el.querySelector('.el-select-dropdown .el-select-dropdown__wrap')
        select_dom.addEventListener('scroll', function() {
          const height = this.scrollHeight - this.scrollTop - 1 <= this.clientHeight
          if (height) {
            binding.value()
          }
        })
      }
    }
  },
  props: {
    oprType: {
      type: String,
      default: OPR_TYPE.ADD
    },
    shopId: {
      type: Number,
      default: 0
    },
    detailId: {
      type: Number,
      default: 0
    },
    shopList: {
      type: Array,
      default: () => []
    }

  },
  data() {
    return {
      OPR_TYPE,
      LIST_STATE,
      formData: {
        userIds: '',
        labelList: [],
        shopId: '',
        userId: ''
      },
      rules: {
        shopId: [{ required: true, message: '请选择门店', trigger: 'blur' }],
        name: [{ required: true, message: '请输入资源名称', trigger: 'blur' }]
      },
      levelList: [],
      // -----上传图片 start-----
      actionUrl: imgUploadUrl,
      uploadHeaders: {},
      // -----上传图片 end-----
      options: {
        row: []
      },
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 0,
      flag: null,
      tagValue: '',
      saveRow: null
    }
  },
  watch: {
    oprType() {
      this.getDetail()
    }
  },
  mounted() {
    this.getDetail()
    this.formData.shopId = this.shopId
    this.selectShopUser(1, 20, this.shopId).then(res => {
      this.options.row = res.data.row
      this.sysInstanceTotalPages = Math.ceil(res.data.total / 20)
      const flag = this.options.row.some(item => {
        return item.id === this.saveRow.id
      })
      !flag && this.saveRow && this.options.row.unshift(this.saveRow)
    }).catch(err => {
      console.log(err)
    })
  },
  methods: {
    async fetchData() {
      if (!this.shopId) return
      const { code, data } = await getAppointmentLevelLis({
        shopId: this.shopId
      })
      if (code === 0) {
        data.map((v) => {
          v.label = v.name
          v.value = v.id
          return v
        })
        this.levelList = [...data]
      }
    },
    goBack() {
      this.$emit('on-list-go-back')
    },
    async getDetail() {
      if (this.oprType === OPR_TYPE.ADD) {
        this.formData = {
          imgUrl: '',
          labelList: [],
          levelId: '',
          name: '',
          shopId: '',
          status: 0,
          userId: '',
          userIds: ''
        }
      } else {
        // 通过接口获取详情
        const { code, data } = await getAppointmentCategoryDetail({ id: this.detailId })
        console.log(this.detailId, code, data, '通过接口获取详情')
        if (code === 0) {
          this.formData = data
          this.saveRow = { name: data.userName, id: data.userId }
          delete this.formData.userName
          delete this.formData.categoryId
          !this.formData.labelList && (this.formData.labelList = [])
        }
      }
      await this.fetchData()
    },
    // -----上传图片 start-----
    handleAvatarSuccess(res, file) {
      if (res.code === 0) {
        const { path, baseUrl } = res.data
        this.formData.imgUrl = baseUrl + path
        this.$refs.ruleForm.clearValidate(['imgUrl'])
      } else {
        this.$message.error(res.msg)
      }
    },
    beforeAvatarUpload(file) {
      return this.beforeUploadImg(file, this, 0, 0, 1.024)
    },
    // -----上传图片 end-----
    addShopLabel() {
      console.log(111, this.formData.labelList)
      if (!this.tagValue) return
      if (this.formData.labelList.length >= 6) return this.$message.warning('最多创建6个标签')
      this.formData.labelList.push(this.tagValue)
      this.tagValue = ''
    },
    handleSubmit() {
      this.$refs.ruleForm.validate(async(validate) => {
        if (validate) {
          this.formData.userIds = [this.formData.userIds]
          const api =
            this.oprType === OPR_TYPE.ADD
              ? addAppointmentCategoryDetail
              : updateAppointmentCategoryDetail
          const { code } = await api(this.formData)
          if (code === 0) {
            this.$message.success('保存成功')
            this.goBack()
          }
        } else {
          this.$message.error('请输入完整信息')
        }
      })
    },
    selectShopUser(pageNum, pageSize, shopId) {
      return new Promise((resolve, reject) => {
        selectShopUser({
          pageNum,
          pageSize,
          shopId
        }).then(res => {
          resolve(res)
        }).catch(err => {
          reject(err)
          this.$message.error(err.msg)
        })
      })
    },
    changeSelect(e) {
      this.sysInstanceIndex = 1
      this.$nextTick(() => {
        this.$set(this.formData, 'userIds', [])
        this.$set(this.formData, 'userId', '')
      })
      this.shopUserApi(e)
    },
    async shopUserApi(e) {
      const { code, data: { row = [], total } } = await this.selectShopUser(this.sysInstanceIndex, 20, e)
      if (code !== 0) return
      this.sysInstanceTotalPages = Math.ceil(total / 20)
      this.options.row = this.flag === e ? [...this.options.row, ...row] : row
      this.flag = e
      const flag = this.options.row.some(item => {
        return item.id === this.saveRow.id
      })
      flag && this.options.row.shift(this.saveRow)
    },
    loadMore() {
      if (this.sysInstanceIndex >= this.sysInstanceTotalPages) return
      this.sysInstanceIndex++
      this.shopUserApi(this.flag)
    }

  }
}
</script>

<style scoped lang="scss">
header {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #9e9e9e;
  padding-bottom: 20px;

  .title {
    font-size: 20px;
    font-weight: bold;
    margin-right: 20px;
  }

  div {
    margin-right: 20px;
  }
}

.main {
  margin-top: 20px;

  .el-select,
  .el-input {
    width: 300px;
  }

  .app-uploader-img-plus {
    width: 180px;
    height: 180px;

    .app-uploader-img-plus-icon {
      font-size: 36px;
      color: #8c939d;
      width: 180px;
      height: 180px;
      line-height: 180px;
      text-align: center;
    }

    .avatar {
      width: 180px;
      height: 180px;
      display: block;
    }
  }

  .upload_tips {
    margin: 20px 0 0 20px;

    li {
      margin-top: 10px;
      font-size: 14px;
      line-height: 16px;
      color: $dark-font-color;
    }
  }
  .i{
    margin-left: 20px;
    color: $dark-font-color;
  }
}
</style>
